package top.infopub.mgr.cap.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.infopub.dto.mkt.InformationSubmitApprovalDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.cap.FinancialTypesEnum;
import top.infopub.enums.cap.LoanStyleEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.InformationSubmitApprovalService;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.model.cap.FinancingApproval;
import top.infopub.model.cap.InformationSubmitApproval;
import top.infopub.model.cap.SetupFinancial;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import top.infopub.enums.cap.FinancialStyleEnum;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;

/**
 * @Author Warking
 * @Date 2021/5/22 12:48
 * @Version 1.0   资料报审
 */
@Controller
@RequestMapping("/submitApproval")
public class InformationSubmitApprovalController {
    @Autowired
    private InformationSubmitApprovalService informationSubmitApprovalService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private CapProcessManageService capProcessManageService;

    /*资料报审列表接口*/
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<InformationSubmitApproval> queryDataByCondition(InformationSubmitApproval informationSubmitApproval, ParamPage paramPage) throws ParseException {
        Page<InformationSubmitApproval> page = new Page();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //处理时间范围
        if (!StringUtils.isEmpty(informationSubmitApproval.getDates())) {
            String[] splitTime = informationSubmitApproval.getDates().split("~");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            informationSubmitApproval.setStartDate(format.parse(splitTime[0]));
            informationSubmitApproval.setEndDate(format.parse(splitTime[1]));
        }
        page = informationSubmitApprovalService.selectPage(page, informationSubmitApproval);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 资料报审详情跳转
     *
     * @return
     */
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("proCode", proCode);
        request.setAttribute("id", id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        InformationSubmitApproval informationSubmitApproval = informationSubmitApprovalService.selectByKey(id);
        if (informationSubmitApproval != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), informationSubmitApproval.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), informationSubmitApproval.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(informationSubmitApproval.getProcessId()) && informationSubmitApproval.getProcessId().length() > 10) {
                request.setAttribute("processId", informationSubmitApproval.getProcessId());
                String auditTabFlag = capProcessManageService.checkShowAuditTab(informationSubmitApproval.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), informationSubmitApproval.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        return "cap/lay-DataSubmission-detail";
    }


    //资料报审详情页面
    @RequestMapping("/queryByIdDetail")
    @ResponseBody
    public InformationSubmitApprovalDto queryDetailById(String id) {
        InformationSubmitApprovalDto dto = informationSubmitApprovalService.queryDetailById(id);
        return dto;
    }

    //资料报审详情金融机构下拉框数据
    @RequestMapping("/queryFinancialDetail")
    @ResponseBody
    public List queryFinancialDetail(String proCode) {
        List<Map<String, String>> list = informationSubmitApprovalService.queryFinancialDetail(proCode);
        return list;
    }

    /*资料报审金融机构下拉框选择事件接口*/
    @RequestMapping("/selectFinancialDetail")
    @ResponseBody
    public SetupFinancial querySetupFinancialDetail(String id, String proCode) {
        SetupFinancial setupFinancial = informationSubmitApprovalService.querySetupFinancialDetail(id, proCode);
        return setupFinancial;
    }

    /*融资方式下拉框*/
    @RequestMapping("/financingStyle")
    @ResponseBody
    public List financingStyle() {
        List<Map<String, String>> list = FinancialStyleEnum.asList();
        return list;
    }

    /*贷款类型下拉框*/
    @RequestMapping("/loanStyleEnum")
    @ResponseBody
    public List LoanStyleEnum() {
        List<Map<String, String>> list = LoanStyleEnum.asList();
        return list;
    }


    /*金融类型下拉框*/
    @RequestMapping("/financingType")
    @ResponseBody
    public List financingType() {
        List<Map<String, String>> list = FinancialTypesEnum.asList();
        return list;
    }

    //资料报审详情 保存提交 前端传一个融资的数据过来
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(String financingApproval, String identifying, String proCode, String id) {
        if (StringUtils.isEmpty(financingApproval)) {
            return RspVo.getFailureResponse(0, "数据为空");
        }
        String object = StringEscapeUtils.unescapeJava(financingApproval);
        FinancingApproval financing = JSON.parseObject(object, FinancingApproval.class);
        //判断标书策划的状态
        InformationSubmitApproval informationSubmitApproval = informationSubmitApprovalService.selectByKey(id);
        if (informationSubmitApproval != null) {
            if ("1".equals(informationSubmitApproval.getProcessStatus()) || "9".equals(informationSubmitApproval.getProcessStatus())) {
                return RspVo.getFailureResponse(0, "审批中或审批已完成，修改失败");
            }
        }
        if ("0".equals(identifying)) {//0是保存
            int i = informationSubmitApprovalService.save(financing, proCode);
            if (i > 0) {
                return RspVo.getSuccessResponse(0, "保存成功");
            } else {
                return RspVo.getFailureResponse(0, "保存失败");
            }
        } else {
            if (informationSubmitApproval != null) {
                if (StringUtils.isNotBlank(informationSubmitApproval.getOaId())) {
                    oaFlowService.finishOA(informationSubmitApproval.getOaId());
                }
            }
            //提交流程  先保存
            int i = informationSubmitApprovalService.save(financing, proCode);
            if (i > 0) {//保存成的情况 走流程
                //登录人员信息
                AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
                //发起流程
                String process = capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE5, object, id, proCode, vo);
                if (!StringUtils.isEmpty(process)) {
                    return RspVo.getSuccessResponse(0, "提交成功");
                }
                return RspVo.getFailureResponse(0, "提交失败");
            } else { //提交-保存失败
                return RspVo.getFailureResponse(0, "提交失败");
            }
        }

    }


    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //立项审批
        capProcessManageService.auditProject(id, processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }

    /*资料报审的融资报审数据审批通过后往融资批复主表写入数据*/
    @RequestMapping("/readInData")
    public List<String> readInData(String proCode, AuthorizationVO vo) {
        /*根据主表proCode查询子表融资报审的数据*/
        return informationSubmitApprovalService.saveFundingApproval(proCode, vo);
    }
}
